import logging
from logging.handlers import RotatingFileHandler

from .settings import *

# global path
__delim = "\\" if sys.platform == "win32" else "/"
__tmp = f"{__delim}util{__delim}log_setup.py"
assert __tmp in __file__
ASHARE_DIR = os.path.realpath(__file__).replace(__tmp, "")
ASHARE_OFFLINE_DIR = os.path.join(ASHARE_DIR, "offline")
ASHARE_LOG_DIR = os.path.join(ASHARE_DIR, "log")
if not os.path.exists(ASHARE_LOG_DIR):
    os.makedirs(ASHARE_LOG_DIR)


class Log:
    format_str = "%(asctime)s [%(levelname)s] %(message)s"
    # format_str = "%(asctime)s [%(levelname)s] [%(filename)s:%(lineno)d] %(message)s"

    @classmethod
    def setup(cls, filename: Optional[str] = None, level: str = LOG_LEVEL):
        for handler in logging.getLogger().handlers[:]:
            logging.getLogger().removeHandler(handler)
        handlers = [logging.StreamHandler()]
        if filename is not None:
            handlers.append(
                RotatingFileHandler(
                    filename,
                    maxBytes=int(1024 * 1024 * 1024 * LOG_ROTATE_FILE_SIZE_IN_GB),
                    backupCount=LOG_ROTATE_FILE_COUNT,
                )
            )
        logging.basicConfig(
            level=level,
            format=cls.format_str,
            handlers=handlers,
        )


logging.getLogger("asyncio").setLevel(logging.WARNING)
logging.getLogger("urllib3").setLevel(logging.WARNING)
logging.getLogger("matplotlib").setLevel(logging.WARNING)

# default to use console
Log.setup()
